//
//  WBTabBar.swift
//  微博(swift)
//
//  Created by 汤米 on 16/4/17.
//  Copyright © 2016年 汤米. All rights reserved.
//

import UIKit
protocol WBTabBarDelegate: NSObjectProtocol {
    
    //协议方法
    func writeButtonWasClick()
}


class WBTabBar: UITabBar {

    //代理属性
    weak var WBdelegate: WBTabBarDelegate?
    
    // MARK: -  重写init方法
   override init(frame: CGRect) {
    
        super.init(frame: frame)
        setUpUI()
    }
    

    // MARK: -  设置UI
    private func setUpUI() {
    
        addSubview(writeButton)
    }
    
    // MARK: -  设置布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let width = kScreenW / 5
        var index: CGFloat = 0
        for value in self.subviews {
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                value.frame.origin.x = index * width
                value.frame.size.width = width
                
                index += 1
                if index==2 {
                    index += 1
                }
                
            }
        }

        writeButton.center.x = self.frame.size.width * 0.5
        writeButton.center.y = self.frame.size.height * 0.5
    }
    
    
    // MARK: -  懒加载撰写按钮
    private lazy var writeButton: UIButton = {
        
        let button = UIButton()
        
        button.addTarget(self, action: "clickWriteButton", forControlEvents: UIControlEvents.TouchUpInside)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.sizeToFit()
        
        return button
    }()
    
    
    // MARK: -  button的点击事件
    @objc private func clickWriteButton() {
        if  WBdelegate==nil {
            print("1111")
            
        }
        WBdelegate?.writeButtonWasClick()
    }
    
    
    // MARK: -  如果重写了init frame 方法  那么一定要实现 init coder 方法
   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
}
